<template>
  <section style="padding:10px;">
    <!--查询-->
    <el-form :inline="true" :model="filters" @submit.native.prevent>
      <el-form-item>
        <el-input
          v-model="filters.label"
          placeholder="视图名或地址"
          clearable
          @keyup.enter.native="onGetList"
        >
          <template #prefix>
            <i class="el-input__icon el-icon-search" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onGetList">查询</el-button>
      </el-form-item>
      <el-form-item v-if="checkPermission(['api:admin:view:add'])">
        <el-button type="primary" @click="onAdd">新增</el-button>
      </el-form-item>
      <el-form-item v-if="checkPermission(['api:admin:view:sync'])">
        <my-confirm-button
          :icon="'el-icon-refresh'"
          :placement="'bottom-end'"
          :loading="syncLoading"
          style="margin:0px;"
          @click="onSync"
        >
          <template #content>
            <p>确定要同步视图吗？</p>
          </template>
          同步视图
        </my-confirm-button>
      </el-form-item>
      <el-form-item v-if="checkPermission(['api:admin:view:batchsoftdelete'])">
        <my-confirm-button
          :disabled="sels.length === 0"
          :type="'delete'"
          :placement="'bottom-end'"
          :loading="deleteLoading"
          style="margin-left: 0px;"
          @click="onBatchDelete"
        >
          <template #content>
            <p>确定要批量删除吗？</p>
          </template>
          批量删除
        </my-confirm-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      row-key="id"
      :data="viewTree"
      :default-expand-all="false"
      :expand-row-keys="expandRowKeys"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      highlight-current-row
      style="width: 100%;"
      @select-all="onSelectAll"
      @select="onSelect"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="50" label="#" />
      <el-table-column prop="label" label="视图名" width="180" />
      <el-table-column prop="id" label="编号" width="80" />
      <el-table-column prop="path" label="视图地址" width />
      <el-table-column prop="description" label="视图描述" width />
      <el-table-column prop="enabled" label="状态" width="100">
        <template #default="{row}">
          <el-tag
            :type="row.enabled ? 'success' : 'info'"
            disable-transitions
          >{{ row.enabled ? '正常' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        v-if="checkPermission(['api:admin:view:update','api:admin:view:softdelete'])"
        label="操作"
        width="180"
      >
        <template #default="{ $index, row }">
          <el-button @click="onCode($index, row)">代码生成</el-button>
          <el-button
            v-if="checkPermission(['api:admin:view:update'])"
            @click="onEdit($index, row)"
          >编辑</el-button>
          <my-confirm-button
            v-if="checkPermission(['api:admin:view:softdelete'])"
            type="delete"
            :loading="row._loading"
            @click="onDelete($index, row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!--新增窗口-->
    <el-dialog
      v-if="checkPermission(['api:admin:view:add'])"
      title="新增"
      :visible.sync="addFormVisible"
      :close-on-click-modal="false"
      @close="onCloseAddForm"
    >
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules">
        <el-form-item prop="parentIds" label="所属模块">
          <el-cascader
            :key="addFormKey"
            v-model="addForm.parentIds"
            placeholder="请选择，支持搜索功能"
            :options="modules"
            :props="{ checkStrictly: true, value: 'id' }"
            filterable
            style="width:100%;"
          />
        </el-form-item>
        <el-form-item label="视图名" prop="label">
          <el-input v-model="addForm.label" auto-complete="off" />
        </el-form-item>
        <el-form-item label="视图地址" prop="path">
          <el-input v-model="addForm.path" auto-complete="off" />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="addForm.enabled" />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="addForm.description" type="textarea" rows="2" auto-complete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="addFormVisible = false">取消</el-button>
          <my-confirm-button
            type="submit"
            :validate="addFormValidate"
            :loading="addLoading"
            @click="onAddSubmit"
          />
        </div>
      </template>
    </el-dialog>

    <!--编辑窗口-->
    <el-dialog
      v-if="checkPermission(['api:admin:view:update'])"
      title="编辑"
      :visible.sync="editFormVisible"
      :close-on-click-modal="false"
      @close="onCloseEditForm"
    >
      <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="80px">
        <el-form-item prop="parentIds" label="所属模块">
          <el-cascader
            :key="editFormKey"
            v-model="editForm.parentIds"
            placeholder="请选择，支持搜索功能"
            :options="modules"
            :props="{ checkStrictly: true, value: 'id' }"
            filterable
            style="width:100%;"
          />
        </el-form-item>
        <el-form-item label="视图名" prop="label">
          <el-input v-model="editForm.label" auto-complete="off" />
        </el-form-item>
        <el-form-item label="视图地址" prop="path">
          <el-input v-model="editForm.path" auto-complete="off" />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="editForm.enabled" />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="editForm.description" type="textarea" rows="2" auto-complete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="editFormVisible = false">取消</el-button>
          <my-confirm-button
            type="submit"
            :validate="editFormValidate"
            :loading="editLoading"
            @click="onEditSubmit"
          />
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="codedata.editFormVisible" width="80%">
      <el-steps :active="codedata.active" finish-status="success">
        <el-step title="准备阶段" />
        <el-step title="步骤 2" />
        <el-step title="步骤 3" />
      </el-steps>
      <template v-if="codedata.active===0">
        1完成后端接口的开发；
        2权限管理-接口管理页面同步api；
        {{ codedata.data }}
      </template>
      <template v-else-if="codedata.active===1">
        <el-form :model="codedata.form" label-width="100px">
          <el-form-item prop="viewcode" label="表单代码">{{ codedata.form.viewcode }}</el-form-item>
          <el-form-item prop="listapi" label="获取列表API接口">
            <el-cascader
              v-model="codedata.form.listapi"
              placeholder="请选择，支持搜索功能"
              style="width: 100%;"
              :options="codedata.apiTree"
              :props="{ value: 'path', label:'path', emitPath:false }"
              filterable
              :show-all-levels="false"
            >
              <template #default="{ data }">
                <span>{{ data.path }}</span>
                <span style="float:right;margin-left:15px;">{{ data.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item prop="addapi" label="新增API接口">
            <el-cascader
              v-model="codedata.form.addapi"
              placeholder="请选择，支持搜索功能"
              style="width: 100%;"
              :options="codedata.apiTree"
              :props="{ value: 'path', label:'path', emitPath:false }"
              filterable
              :show-all-levels="false"
            >
              <template #default="{ data }">
                <span>{{ data.path }}</span>
                <span style="float:right;margin-left:15px;">{{ data.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item prop="delapi" label="删除API接口">
            <el-cascader
              v-model="codedata.form.delapi"
              placeholder="请选择，支持搜索功能"
              style="width: 100%;"
              :options="codedata.apiTree"
              :props="{ value: 'path', label:'path', emitPath:false }"
              filterable
              :show-all-levels="false"
            >
              <template #default="{ data }">
                <span>{{ data.path }}</span>
                <span style="float:right;margin-left:15px;">{{ data.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item prop="updateapi" label="修改API接口">
            <el-cascader
              v-model="codedata.form.updateapi"
              placeholder="请选择，支持搜索功能"
              style="width: 100%;"
              :options="codedata.apiTree"
              :props="{ value: 'path', label:'path', emitPath:false }"
              filterable
              :show-all-levels="false"
            >
              <template #default="{ data }">
                <span>{{ data.path }}</span>
                <span style="float:right;margin-left:15px;">{{ data.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-form>
      </template>
      <template v-else-if="codedata.active===2">
        <basic-container>
          <avue-crud
            :data="codedata.tabledata"
            :option="codedata.tableoption"
            @row-update="rowUpdate"
            @row-save="rowSave"
            @row-del="rowDel"
          />
        </basic-container>
      </template>
      <template v-else-if="codedata.active===3">
        <el-tabs v-model="codedata.codeactiveName">
          <el-tab-pane label="后台代码" name="first">
            <el-input
              v-model="codedata.result.csharp"
              type="textarea"
              :rows="20"
              placeholder="请输入内容"
            />
          </el-tab-pane>
          <el-tab-pane label="前端api代码" name="second">
            <div>
              把代码放在/api{{ codedata.form.viewcode }}.js内
              <el-input
                v-model="codedata.result.jsapi"
                type="textarea"
                :rows="20"
                placeholder="请输入内容"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="前端option代码" name="third">
            <div>
              把代码放在/option{{ codedata.form.viewcode }}.js内
              <el-input
                v-model="codedata.result.jsoption"
                type="textarea"
                :rows="20"
                placeholder="请输入内容"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="前端vue代码" name="fourth">
            <div>
              把代码放在/views{{ codedata.form.viewcode }}.js内
              <el-input
                v-model="codedata.result.jsvue"
                type="textarea"
                :rows="20"
                placeholder="请输入内容"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <el-button style="margin-top: 12px;" @click="next">下一步</el-button>
      <el-button v-if="codedata.active===3" style="margin-top: 12px;" @click="synccode">同步</el-button>
    </el-dialog>
  </section>
</template>

<script>
import { formatTime, treeToList, listToTree, getTreeParents } from '@/utils'
import { getApiList } from '@/api/admin/api'
import {
  removeView,
  editView,
  addView,
  syncView,
  getViewList,
  batchRemoveView,
  getView, SaveCode
} from '@/api/admin/view'
import MyConfirmButton from '@/components/my-confirm-button'
import { getresult } from '@/utils/handlebars/index.js'
export default {
  name: 'V',
  components: {
    MyConfirmButton
  },
  data() {
    return {
      codedata: {
        result: {
          csharp: ''
        },
        active: 0,
        codeactiveName: 'second',
        editFormVisible: false,
        data: {},
        apiTree: [],
        form: {},
        tabledata: [],
        tableoption: {
          labelWidth: 180,
          title: '表格的标题',
          sortable: true,
          page: false,
          align: 'center',
          menuAlign: 'center',

          column: [
            {
              label: '栏位代码',
              prop: 'code',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '栏位名称',
              prop: 'name',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '控件类型',
              prop: 'type',
              value: 'input',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              type: 'select',
              dicData: [
                {
                  value: 'cascader',
                  label: '级联框cascader'
                },
                {
                  value: 'checkbox',
                  label: '多选框checkbox'
                },
                {
                  value: 'date',
                  label: '日期框date'
                },
                {
                  value: 'datetime',
                  label: '日期时间框datetime'
                },
                {
                  value: 'daterange',
                  label: '日期范围daterange'
                },
                {
                  value: 'datetimerange',
                  label: '日期时间范围datetimerange'
                },
                {
                  value: 'dates',
                  label: '多个日期dates'
                },
                {
                  value: 'dynamic',
                  label: '动态输入框dynamic'
                },
                {
                  value: 'input',
                  label: '输入框input'
                },
                {
                  value: 'month',
                  label: '月month'
                },
                {
                  value: 'password',
                  label: '密码框password'
                },
                {
                  value: 'radio',
                  label: '单选框radio'
                },
                {
                  value: 'select',
                  label: '选择框select'
                },
                {
                  value: 'switch',
                  label: '开关框switch'
                },
                {
                  value: 'textarea',
                  label: '文本框textarea'
                },
                {
                  value: 'time',
                  label: '时间框time'
                },
                {
                  value: 'timerange',
                  label: '时间范围timerange'
                },
                {
                  value: 'tree',
                  label: '树框tree'
                },
                {
                  value: 'week',
                  label: '周week'
                },
                {
                  value: 'year',
                  label: '年year'
                }
              ]
            },
            {
              label: '必填',
              prop: 'required',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            },
            {
              label: '查询条件',
              prop: 'search',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            },
            {
              label: '新增时是否禁止',
              prop: 'addDisabled',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            },
            {
              label: '新增时是否可见',
              prop: 'addDisplay',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            },
            {
              label: '新增时是否为查看模式',
              prop: 'addDetail',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            },
            {
              label: '编辑时是否禁止',
              prop: 'editDisabled',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            },
            {
              label: '编辑时是否可见',
              prop: 'editDisplay',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            },
            {
              label: '编辑时是否为查看模式',
              prop: 'editDetail',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            },
            {
              label: '在列表显示',
              prop: 'showColumn',
              type: 'radio',
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              dicData: [
                {
                  label: '是',
                  value: true
                },
                {
                  label: '否',
                  value: false
                }
              ]
            }
          ]
        }
      },
      filters: {
        label: ''
      },
      viewTree: [],
      expandRowKeys: [],
      listLoading: false,
      sels: [], // 列表选中列

      addDialogFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      editFormRules: {
        parentIds: [
          { required: true, message: '请选择所属模块', trigger: 'change' }
        ],
        path: [{ required: true, message: '请输入视图地址', trigger: 'blur' }],
        label: [{ required: true, message: '请输入视图名', trigger: 'blur' }]
      },
      // 编辑界面数据
      editForm: {
        id: 0,
        parentIds: [],
        path: '',
        label: '',
        enabled: false,
        description: ''
      },
      editFormKey: 1,

      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addFormRules: {
        parentIds: [
          { required: true, message: '请选择所属模块', trigger: 'change' }
        ],
        path: [{ required: true, message: '请输入视图地址', trigger: 'blur' }],
        label: [{ required: true, message: '请输入视图名', trigger: 'blur' }]
      },
      // 新增界面数据
      addForm: {
        parentIds: [],
        path: '',
        label: '',
        enabled: true,
        description: ''
      },
      addFormKey: 1,
      modules: [],
      syncLoading: false,
      deleteLoading: false
    }
  },
  mounted() {
    this.onGetList()
    this.getApiList()
  },
  methods: {
    rowSave(row, done, loading) {
      this.codedata.tabledata.push(row)
      done()
    },
    rowUpdate(row, index, done, loading) {
      this.codedata.tabledata.splice(index, 1, row)
      done()
    },
    rowDel(row, index) {
      this.codedata.tabledata.splice(index, 1)
    },
    async getApiList() {
      const res = await getApiList()
      if (res && res.success) {
        this.codedata.apiTree = listToTree(_.cloneDeep(res.data))
      }
    },
    synccode() {
      this.codedata.result.viewcode = this.codedata.form.viewcode
      SaveCode(this.codedata.result).then(re => {

      })
    },
    next() {
      if (this.codedata.active === 0) {
        this.codedata.active = 1
      } else if (this.codedata.active === 1) {
        this.codedata.active = 2
      } else if (this.codedata.active === 2) {
        this.codedata.active = 3
        this.codedata.result.csharp = getresult('csharp', this.codedata)
        this.codedata.result.jsapi = getresult('jsapi', this.codedata)

        this.codedata.result.jsoption = getresult('jsoption', this.codedata)

        this.codedata.result.jsvue = getresult('jsvue', this.codedata)
      }
    },
    formatCreatedTime: function(row, column, time) {
      return formatTime(time, 'YYYY-MM-DD HH:mm')
    },
    // 获取列表
    async onGetList() {
      const para = {
        key: this.filters.label
      }
      this.listLoading = true
      const res = await getViewList(para)
      this.listLoading = false

      if (!res?.success) {
        return
      }

      const list = _.cloneDeep(res.data)

      const keys = list.filter((l) => l.parentId === 0).map((l) => l.id + '')
      this.expandRowKeys = keys

      this.modules = listToTree(_.cloneDeep(list), {
        id: 0,
        parentId: 0,
        label: '根节点'
      })

      list.forEach((l) => {
        l._loading = false
      })

      const tree = listToTree(list)
      this.sels = []
      this.viewTree = tree
    },
    async onCode(index, row) {
      this.codedata.form.viewcode = row.path
      this.codedata.form.viewcode1 = row.path
      if (row.path.startsWith('/')) {
        this.codedata.form.viewcode1 = this.codedata.form.viewcode1.replace(
          '/',
          ''
        )
      }

      this.codedata.active = 0
      this.codedata.data = row
      this.codedata.editFormVisible = true
    },

    // 显示编辑界面
    async onEdit(index, row) {
      const loading = this.$loading()
      const res = await getView({ id: row.id })
      loading.close()
      if (res && res.success) {
        const parents = getTreeParents(this.viewTree, row.id)
        const parentIds = parents.map((p) => p.id)
        parentIds.unshift(0)

        const data = res.data
        data.parentIds = parentIds
        this.editForm = data
        this.editFormVisible = true
        ++this.editFormKey
      }
    },
    onCloseEditForm() {
      this.$refs.editForm.resetFields()
      ++this.editFormKey
    },
    // 显示新增界面
    onAdd() {
      this.addFormVisible = true
    },
    onCloseAddForm() {
      this.$refs.addForm.resetFields()
      ++this.addFormKey
    },
    // 编辑
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate((valid) => {
        isValid = valid
      })
      return isValid
    },
    async onEditSubmit() {
      this.editLoading = true
      const para = _.cloneDeep(this.editForm)
      para.parentId = para.parentIds.pop()
      if (para.id === para.parentId) {
        this.$message({
          message: '所属模块不能是自己！',
          type: 'error'
        })
        this.editLoading = false
        return
      }

      const res = await editView(para)
      this.editLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.updateOk'),
        type: 'success'
      })
      this.$refs['editForm'].resetFields()
      this.editFormVisible = false
      this.onGetList()
    },
    // 新增
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate((valid) => {
        isValid = valid
      })
      return isValid
    },
    async onAddSubmit() {
      this.addLoading = true
      const para = _.cloneDeep(this.addForm)
      para.parentId = para.parentIds.pop()

      const res = await addView(para)
      this.addLoading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.addOk'),
        type: 'success'
      })
      this.$refs['addForm'].resetFields()
      this.addFormVisible = false
      this.onGetList()
    },
    // 删除
    async onDelete(index, row) {
      row._loading = true
      const para = { id: row.id }
      const res = await removeView(para)

      row._loading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.deleteOk'),
        type: 'success'
      })
      this.onGetList()
    },
    // 批量删除
    async onBatchDelete() {
      const para = { ids: [] }
      para.ids = this.sels.map((s) => {
        return s.id
      })

      this.deleteLoading = true
      const res = await batchRemoveView(para.ids)
      this.deleteLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.batchDeleteOk'),
        type: 'success'
      })

      this.onGetList()
    },
    // 同步view
    async onSync() {
      const unFinish = true
      if (unFinish) {
        this.$message({
          message: '开发中',
          type: 'info'
        })
        return
      }

      const views = []
      this.syncLoading = true
      const syncRes = await syncView({ views })
      this.syncLoading = false

      if (!syncRes?.success) {
        return
      }

      this.$message({
        message: this.$t('view.sync'),
        type: 'success'
      })
      this.onGetList()
    },
    // 生成前端view
    onGenerate() {
      // let bb = this.sels
    },
    onSelectAll: function(selection) {
      const selections = treeToList(selection)
      const rows = treeToList(this.viewTree)
      const checked = selections.length === rows.length
      rows.forEach((row) => {
        this.$refs.multipleTable.toggleRowSelection(row, checked)
      })

      this.sels = this.$refs.multipleTable.selection
    },
    onSelect: function(selection, row) {
      const checked = selection.some((s) => s.id === row.id)
      if (row.children && row.children.length > 0) {
        const rows = treeToList(row.children)
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row, checked)
        })
      }

      this.sels = this.$refs.multipleTable.selection
    }
  }
}
</script>
